package substr

//Join the substrings of s with sep.
func Join(s *S, sep []byte) []byte {
	if len(s.Subs) == 0 {
		return nil
	}
	sz := 0
	for _, v := range s.Subs {
		sz += v[1] - v[0]
	}
	if sz == 0 {
		return nil
	}
	out := make([]byte, sz+(len(s.Subs)-1)*len(sep))
	last := 0
	for i, v := range s.Subs {
		sz := v[1] - v[0]
		copy(out[last:last+sz], s.Super[v[0]:v[1]])
		last += sz
		if i+1 < len(s.Subs) {
			copy(out[last:last+len(sep)], sep)
			last += len(sep)
		}
	}
	return out
}
